package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.domain.Travel;
import cn.wolfcode.trip.base.domain.Travelcontent;
import cn.wolfcode.trip.base.mapper.TravelMapper;
import cn.wolfcode.trip.base.mapper.TravelContentMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.query.TravelQueryObject;
import cn.wolfcode.trip.base.service.ITravelService;
import cn.wolfcode.trip.base.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class TravelServiceImpl implements ITravelService {

    @Autowired
    private TravelMapper travelMapper;
    @Autowired
    private TravelContentMapper travelContentMapper;

    @Override
    public void update(Travel travel) {
        //更新时间
        travel.setLastUpdateTime(new Date());
        travelMapper.updateByPrimaryKey(travel);
        Travelcontent travelcontent = new Travelcontent();
        travelcontent.setId(travel.getId());
        travelcontent.setContent(travel.getTravelContent().getContent());
        travelContentMapper.updateByPrimaryKey(travelcontent);
    }

    @Override
    public void save(Travel travel) {
        Date date=new Date();

        //作者
        travel.setAuthor(UserContext.getCurrentUser());
        //创建时间
        travel.setCreateTime(date);
        //更新时间
        travel.setLastUpdateTime(date);

        travelMapper.insert(travel);

        Travelcontent travelcontent = new Travelcontent();
        travelcontent.setId(travel.getId());
        travelcontent.setContent(travel.getTravelContent().getContent());
        travelContentMapper.insert(travelcontent);
    }

    @Override
    public Travel get(Long id) {
        return  travelMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Travel> listAll() {
        return null;
    }

    /**
     * 分页及排序
     * @param qo
     * @return
     */
    @Override
    public PageInfo<Travel> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),qo.getOrderBy());
        List<Travel> list=travelMapper.selectForlist(qo);
        return new PageInfo<>(list);
    }

    @Override
    public void changeState(Travel travel) {
        if(travel.getState()==2){
            //发布需要发布时间
            travel.setReleaseTime(new Date());
        }
        travelMapper.updateStateById(travel);
    }

    @Override
    public PageInfo getTraversCounts(TravelQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Strategy> list=travelMapper.selectList(qo);
        return new PageInfo<>(list);
    }



    @Override
    public Travel getById(Long id) {
        return travelMapper.get(id);
    }
}
